const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 获取所有分类
async function getAllCategories() {
  try {
    const result = await db.collection('service_categories')
      .where({
        status: 'active'
      })
      .orderBy('sortOrder', 'asc')
      .get()
    
    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 根据分类代码获取分类
async function getCategoryByCode(categoryCode) {
  try {
    const result = await db.collection('service_categories')
      .where({
        code: categoryCode,
        status: 'active'
      })
      .get()
    
    return {
      success: true,
      data: result.data[0] || null
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 添加分类
async function addCategory(categoryData) {
  try {
    const now = new Date()
    const result = await db.collection('service_categories').add({
      data: {
        ...categoryData,
        createTime: now,
        updateTime: now,
        status: 'active'
      }
    })
    
    return {
      success: true,
      data: { _id: result._id, ...categoryData }
    }
  } catch (error) {
    console.error('添加分类失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 更新分类
async function updateCategory(categoryId, updateData) {
  try {
    const result = await db.collection('service_categories').doc(categoryId).update({
      data: {
        ...updateData,
        updateTime: new Date()
      }
    })
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('更新分类失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 删除分类（软删除）
async function deleteCategory(categoryId) {
  try {
    const result = await db.collection('service_categories').doc(categoryId).update({
      data: {
        status: 'deleted',
        updateTime: new Date()
      }
    })
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('删除分类失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 初始化分类数据
async function initCategoryData() {
  try {
    // 检查是否已有数据
    const existingResult = await db.collection('service_categories').count()
    if (existingResult.total > 0) {
      return {
        success: true,
        message: '分类数据已存在，无需初始化',
        data: []
      }
    }

    const categories = [
      {
        code: 'sme_market',
        name: '中小市场',
        icon: '🏢',
        description: '中小企业市场拓展与营销策划服务',
        color: '#667eea',
        sortOrder: 1
      },
      {
        code: 'info_integration',
        name: '信息化集成',
        icon: '💻',
        description: '企业信息化系统集成与优化',
        color: '#f093fb',
        sortOrder: 2
      },
      {
        code: 'engineering',
        name: '工程施工',
        icon: '🏗️',
        description: '各类工程项目施工与管理',
        color: '#4facfe',
        sortOrder: 3
      },
      {
        code: 'network_maintenance',
        name: '网络维护',
        icon: '🔧',
        description: '网络设备维护与故障排除',
        color: '#43e97b',
        sortOrder: 4
      },
      {
        code: 'smart_home',
        name: '智能家居',
        icon: '🏠',
        description: '智能家居系统设计与安装',
        color: '#fa709a',
        sortOrder: 5
      },
      {
        code: 'measurement',
        name: '计量检测',
        icon: '📏',
        description: '专业计量检测与认证服务',
        color: '#667eea',
        sortOrder: 6
      },
      {
        code: 'materials',
        name: '材料设备',
        icon: '📦',
        description: '建筑材料与设备供应服务',
        color: '#f093fb',
        sortOrder: 7
      },
      {
        code: 'construction_team',
        name: '施工队伍',
        icon: '👷',
        description: '专业施工队伍组织与管理',
        color: '#4facfe',
        sortOrder: 8
      },
      {
        code: 'qualification',
        name: '企业资质',
        icon: '📋',
        description: '企业资质申请与认证服务',
        color: '#43e97b',
        sortOrder: 9
      },
      {
        code: 'case_sharing',
        name: '案例分享',
        icon: '📚',
        description: '优秀项目案例分享与交流',
        color: '#fa709a',
        sortOrder: 10
      }
    ]

    const now = new Date()
    const insertData = categories.map(category => ({
      ...category,
      createTime: now,
      updateTime: now,
      status: 'active'
    }))

    const result = await db.collection('service_categories').add({
      data: insertData
    })

    return {
      success: true,
      message: '分类数据初始化成功',
      data: insertData
    }
  } catch (error) {
    console.error('初始化分类数据失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { action } = event

  switch (action) {
    case 'getAllCategories':
      return await getAllCategories()
    
    case 'getCategoryByCode':
      return await getCategoryByCode(event.categoryCode)
    
    case 'addCategory':
      return await addCategory(event.categoryData)
    
    case 'updateCategory':
      return await updateCategory(event.categoryId, event.updateData)
    
    case 'deleteCategory':
      return await deleteCategory(event.categoryId)
    
    case 'initCategoryData':
      return await initCategoryData()
    
    default:
      return {
        success: false,
        error: '未知的操作类型'
      }
  }
} 